package cn.yitun.chat.yitunserverimapicore.business.chat.service.impl;

import cn.yitun.chat.yitunservercommonlib.crud.yitun.BaseVo;
import cn.yitun.chat.yitunservercommonlib.dataentity.data.base.chat.ChatItem;
import cn.yitun.chat.yitunservercommonlib.dataentity.data.message.chat.Content;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.group.GroupChatContentDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.group.GroupMemberVo;
import cn.yitun.chat.yitunservercommonlib.util.NumUtil;
import cn.yitun.chat.yitunservercommonlib.util.R;
import cn.yitun.chat.yitunservercommonlib.util.codec.IdGen;
import cn.yitun.chat.yitunserverimapicore.business.chat.service.GroupChatService;
import cn.yitun.chat.yitunserverimapicore.mq.GroupChatQueue;
import cn.yitun.chat.yitunserverimbase.dao.group.GroupMemberDao;
import cn.yitun.chat.yitunserverimcore.general.main.biz.chat.manager.ChatManager;
import cn.yitun.chat.yitunserverimcore.general.main.push.chat.GroupChatPush;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 
 * Date 2019-02-17 12:14:31<br>
 * Description
 *
 * @author yitun<br>
 * @version 1.1
 */
@Service
@Slf4j
public class GroupChatServiceImpl implements GroupChatService {

	@Resource
	private GroupChatPush groupChatPush;
	@Resource
	private GroupMemberDao groupMemberDAO;
	@Resource
	private ChatManager chatManager;
	@Resource
	private GroupChatQueue groupChatQueue;

	/**
	 * 群聊天
	 * @param key
	 * @param query
	 */
	public void groupChat(Long key, GroupChatContentDto query) {
		Content content = query.getContent();
		if (NumUtil.isInValid(content.getKey())) {
			content.setKey(IdGen.getNumber());
		}
		List<GroupMemberVo> list = groupMemberDAO.listVO(R.param("groupId", query.getGroupId()));
		List<ChatItem> chatItemList = chatManager.wordsFilter(content);

		//TODO 使用群成员列表来组装可能效率不高，后面可能需要使用channelGroup这种来
		List<Long> ids = list.stream().map(GroupMemberVo::getUserId).collect(Collectors.toList());
		groupChatPush.groupChat(IdGen.getNumber(), query.getGroupId(), query.getUserId(), content, ids);
		groupChatQueue.add(query.getGroupId(), query.getUserId(), content, chatItemList);

	}
}
